// 抽象构件
class Component {
    constructor(name) {
        this.name = name
    }
    operation () {
        console.log(this.name + '执行操作')
    }
    add (component) {
        console.log('不支持的操作')
    }
    remove (component) {
        console.log('不支持的操作')
    }
    getChild (index) {
        console.log('不支持的操作')
    }
}

// 叶子节点
class Leaf extends Component {
    constructor(name) {
        super(name)
    }
}

// 树枝节点
class Composite extends Component {
    constructor(name) {
        super(name)
        this.children = []
    }
    add (component) {
        this.children.push(component)
    }
    remove (component) {
        const index = this.children.indexOf(component)
        if (index >= 0) {
            this.children.splice(index, 1)
        }
    }
    getChild (index) {
        return this.children[index]
    }
}

// 使用组合模式
const root = new Component('根')
const branch1 = new Composite('树枝1')
const branch2 = new Composite('树枝2')
const leaf1 = new Leaf('叶子1')
const leaf2 = new Leaf('叶子2')
const leaf3 = new Leaf('叶子3')

root.add(branch1)
root.add(branch2)
branch1.add(leaf1)
branch1.add(leaf2)
branch2.add(leaf3)

root.operation()
branch1.operation()

branch1.remove(leaf2)
branch2.operation()

branch1.getChild(0).operation()